package com.tron.utils.tron;


import com.google.protobuf.ByteString;
import com.tron.entity.TronAccount;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.springframework.stereotype.Component;
import org.tron.trident.abi.FunctionReturnDecoder;
import org.tron.trident.abi.TypeReference;
import org.tron.trident.abi.datatypes.Address;
import org.tron.trident.abi.datatypes.Function;
import org.tron.trident.abi.datatypes.generated.Uint256;
import org.tron.trident.core.ApiWrapper;
import org.tron.trident.core.contract.Contract;
import org.tron.trident.core.contract.Trc20Contract;
import org.tron.trident.core.exceptions.IllegalException;
import org.tron.trident.core.key.KeyPair;
import org.tron.trident.core.utils.ByteArray;
import org.tron.trident.crypto.SECP256K1;
import org.tron.trident.proto.Chain;
import org.tron.trident.proto.Response;
import org.tron.trident.utils.Base58Check;
import org.tron.trident.utils.Numeric;

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;


import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;


@Slf4j
@Component
public class TronUtils implements TronService {
    private String apiKey="5b75cdb4-919a-4f0a-9daa-f07b54c24843";

    private String usdtAddress="TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t";

    /**
     * 手续费的限制
     */
    private Long feeLimit=15000000L;
    /**
     * 合约精度
     */
    private final BigDecimal decimal = new BigDecimal("1000000");

    /**
     * 处理精度
     *
     * @param num
     * @return
     */
    private BigDecimal getNum(int num) {
        StringBuffer buffer = new StringBuffer("1");
        for (int i = 0; i < num; i++) {
            buffer.append("0");
        }
        return new BigDecimal(buffer.toString());
    }


    /**
     * TRC20转账
     *
     * @param toAddress to地址
     * @param amount    金额
     * @return txid
     */
    @Override
    public String sendTRC20USDTTransaction(String privateKey, String fromAddress, String toAddress, BigDecimal amount) {
        ApiWrapper apiWrapper = ApiWrapper.ofMainnet(privateKey, apiKey);
        //ApiWrapper apiWrapper = ApiWrapper.ofNile(privateKey);
        //ApiWrapper apiWrapper = new ApiWrapper("grpc.nile.trongrid.io:50051", "grpc.nile.trongrid.io:50061", "0x" + privateKey);
        //去除无效0
        //amount = amount.divide(BigDecimal.valueOf(100000));
        System.out.println(amount);

        log.info("TRC20转账==> fromAddress:{}, toAddress:{},price:{}", fromAddress, toAddress, amount);
        //合约地址
        Contract contract = apiWrapper.getContract(usdtAddress);
        Trc20Contract token = new Trc20Contract(contract, fromAddress, apiWrapper);

        int scale = amount.scale();
        System.out.println(scale);
        int price = amount.multiply(getNum(scale)).intValue();

        log.info("发起交易==>fromAddress:{},toAddress:{},contractAccress:{},price:{},scale:{}", fromAddress, toAddress, usdtAddress, price, scale);
        System.out.println(fromAddress + ":" + toAddress + ":" + usdtAddress + ":" + price + ":" + scale);

        String txid = token.transfer(toAddress, price, 6 - scale, "memo", feeLimit);
        log.info("交易id==> {}", txid);
        apiWrapper.close();
        return txid;
    }

    @Override
    public String sendTRC10Transaction(String privateKey, String fromAddress, String toAddress, String contractAddress, Long amount) {
        ApiWrapper apiWrapper = ApiWrapper.ofMainnet(privateKey, apiKey);
        //ApiWrapper apiWrapper = ApiWrapper.ofNile(privateKey);
        //ApiWrapper apiWrapper = new ApiWrapper("grpc.nile.trongrid.io:50051", "grpc.nile.trongrid.io:50061", "0x" + privateKey);
        log.info("TRC10转账==> fromAddress:{}, toAddress:{},price:{}", fromAddress, toAddress, amount);
        Response.Account account = apiWrapper.getAccount(contractAddress);
        if (account == null) {
            return null;
        } else {
            ByteString tokenId = account.getAssetIssuedID();
            try {
                Response.TransactionExtention transaction = apiWrapper.transferTrc10(fromAddress, toAddress, Integer.parseInt(tokenId.toString()), amount);
                Chain.Transaction signedTxn = apiWrapper.signTransaction(transaction);
                String txid = apiWrapper.broadcastTransaction(signedTxn);
                log.info("交易id==>{}", txid);
                return txid;
            } catch (IllegalException e) {
                e.printStackTrace();
            } finally {
                apiWrapper.close();
            }
            return null;
        }
    }

    /**
     * TRC转账
     *
     * @param toAddress to地址
     * @return txid
     */
    @Override
    public String sendTRXTransaction(String fromAddress, String privateKey, String toAddress, Long amount) {
        ApiWrapper apiWrapper = ApiWrapper.ofMainnet(privateKey, apiKey);
        //ApiWrapper apiWrapper = ApiWrapper.ofNile(privateKey);
        //ApiWrapper apiWrapper = new ApiWrapper("grpc.nile.trongrid.io:50051", "grpc.nile.trongrid.io:50061", "0x" + privateKey);

       // amount = amount * 1000000;

        log.info("TRX转账==> fromAddress:{}, toAddress:{},price:{}", fromAddress, toAddress, amount);
        try {
            Response.TransactionExtention transaction = apiWrapper.transfer(fromAddress, toAddress, amount);
            Chain.Transaction signedTxn = apiWrapper.signTransaction(transaction);
            String txid = apiWrapper.broadcastTransaction(signedTxn);
            System.out.println(txid);
            log.info("交易id==>{}", txid);
            return txid;
        } catch (IllegalException e) {
            e.printStackTrace();
        } finally {
            apiWrapper.close();
        }
        return null;
    }

    public boolean checkIfTronAddressTrue(String address1, String privateKey) {
        try {
            SECP256K1.PrivateKey privateKey1 = SECP256K1.PrivateKey.create(privateKey);
            SECP256K1.PublicKey publicKey1 = SECP256K1.PublicKey.create(privateKey1);
            String address = KeyPair.publicKeyToBase58CheckAddress(publicKey1);
            if (address.equals(address1)) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            return false;
        }
    }

    /**
     * 生成地址
     */
    @Override
    public TronAccount generateAddress() {
        KeyPair keyPair = KeyPair.generate();
        String privateKey = keyPair.toPrivateKey();

        SECP256K1.PrivateKey privateKey1 = SECP256K1.PrivateKey.create(privateKey);
        SECP256K1.PublicKey publicKey1 = SECP256K1.PublicKey.create(privateKey1);

        String address = KeyPair.publicKeyToBase58CheckAddress(publicKey1);

        TronAccount tronAccount=new TronAccount(address,privateKey,0L,0,1);
        log.info("创建新地址：=> {}", tronAccount);
        return tronAccount;
    }
    /**
     * 获取最新的区块号码
     */
    public Long getLatestBlockNum(String privateKey) {
        ApiWrapper apiWrapper = ApiWrapper.ofMainnet(privateKey, apiKey);
        // ApiWrapper apiWrapper = ApiWrapper.ofNile(privateKey);
        //ApiWrapper apiWrapper = new ApiWrapper("grpc.nile.trongrid.io:50051", "grpc.nile.trongrid.io:50061", "0x" + privateKey);
        try {
            Chain.Block nowBlock = apiWrapper.getNowBlock();
            long number = nowBlock.getBlockHeader().getRawData().getNumber();
            return number;
        } catch (IllegalException e) {
            e.printStackTrace();
        } finally {
            apiWrapper.close();
        }
        return null;
    }


    /**
     * 查询TRC20的余额
     */
    @Override
    public BigInteger searchTRC20Balance(String privateKey, String accountAddr) {
        ApiWrapper apiWrapper = ApiWrapper.ofMainnet(privateKey, apiKey);
        //ApiWrapper apiWrapper = ApiWrapper.ofNile("0x" + privateKey);
        //ApiWrapper apiWrapper = new ApiWrapper("grpc.nile.trongrid.io:50051", "grpc.nile.trongrid.io:50061", "0x" + privateKey);
        try {
            //construct the funtion
            Function balanceOf = new Function("balanceOf",
                    Arrays.asList(new Address(accountAddr)), Arrays.asList(new TypeReference<Uint256>() {
            }));
            //call the function
            Response.TransactionExtention txnExt = apiWrapper.constantCall("THPvaUhoh2Qn2y9THCZML3H815hhFhn5YC", usdtAddress, balanceOf);
            //Convert constant result to human readable text
            String result = Numeric.toHexString(txnExt.getConstantResult(0).toByteArray());
            System.out.println(txnExt.getConstantResult(0));
            System.out.println(txnExt.getConstantResultList());
            return (BigInteger) FunctionReturnDecoder.decode(result, balanceOf.getOutputParameters()).get(0).getValue();
        } catch (Exception e) {
            System.out.println(e.getMessage());
            log.error("处理TRC20余额失败，错误信息:{}", e.toString());
            return null;
        } finally {
            apiWrapper.close();
        }
    }

    public static String stringToHex(String input) {
        StringBuilder hexString = new StringBuilder();

        for (char character : input.toCharArray()) {
            String hex = Integer.toHexString(character);
            hexString.append(hex);
        }

        return hexString.toString();
    }


    private static Response.MarketOrderPair getMarketOrderPair() {
        ByteString buyTokenId = null;
        ByteString sellTokenId = null;
        try {
            buyTokenId = ByteString.copyFrom(ByteArray.fromHex(stringToHex("_")), "utf-8");
            sellTokenId = ByteString.copyFrom(ByteArray.fromHex(stringToHex("_")), "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
        return Response.MarketOrderPair.newBuilder()
                .setBuyTokenId(buyTokenId)
                .setSellTokenId(sellTokenId).build();
    }

    //    public void getMarketPriceByPair(String privateKey) {
//        ApiWrapper apiWrapper = null;
//        try {
//            //apiWrapper = ApiWrapper.ofMainnet(privateKey, apiKey);
//            apiWrapper = ApiWrapper.ofNile(privateKey);
//            Response.MarketOrderPair marketOrderPair = getMarketOrderPair();
//            if(marketOrderPair == null){
//                log.error("获得Market order 的价格pair失败");
//                return null;
//            }
//            return apiWrapper.blockingStub.getMarketPriceByPair(marketOrderPair).;
//        } catch (Exception e) {
//            System.out.println(e.getMessage());
//            log.error("获取Trx余额失败，错误信息:{}", e.toString());
//            return 0L;
//        } finally {
//            apiWrapper.close();
//        }
//    }

    public static double getTrxToUsdtRate() {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        CloseableHttpClient httpClient = HttpClients.custom()
                .setDefaultCredentialsProvider(credsProvider)
                .build();
        HttpGet httpGet = new HttpGet("https://abc.endjgfsv.link/swap/scan/priceinfo");

        HttpResponse response;
        String jsonResponse;
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode jsonNode = null;
        try {
            response = httpClient.execute(httpGet);
            jsonResponse = EntityUtils.toString(response.getEntity());
            jsonNode = objectMapper.readTree(jsonResponse);
        } catch (IOException e) {
            e.printStackTrace();
            return 0.0;
        }

        // Extract the "data" field from the JSON response
        JsonNode dataNode = jsonNode.get("data");

        if (dataNode != null) {
            double rate = dataNode.asDouble();
            System.out.println(rate);
            return Math.round(rate * 100.0) / 100.0; // Round to three decimal places
        } else {
            return 0.0;
        }
    }


    /**
     * 查询trx的余额
     */
    @Override
    public Long searchTrcBalance(String address, String privateKey) {
        ApiWrapper apiWrapper=null;
      try {
           apiWrapper = ApiWrapper.ofMainnet(privateKey, apiKey);
      }catch (Exception e){
          log.error("获取TRX余额异常! 账户:"+address+",私钥:"+privateKey);
          return 0L;
      }


//         ApiWrapper apiWrapper = ApiWrapper.ofNile(privateKey);
      // ApiWrapper apiWrapper = new ApiWrapper("grpc.nile.trongrid.io:50051", "grpc.nile.trongrid.io:50061", "0x" + privateKey);
        try {
            return apiWrapper.getAccount(address).getBalance();
        } catch (Exception e) {
            System.out.println(e.getMessage());
            log.error("获取Trx余额失败，错误信息:{}", e.toString());
            return 0L;
        } finally {
            apiWrapper.close();
        }
    }


    //冻结资金
    public String freeze(long amount, String owneraddress, String privateKey, int resourcecode) {
        ApiWrapper apiWrapper = ApiWrapper.ofMainnet(privateKey, apiKey);
        //ApiWrapper apiWrapper = ApiWrapper.ofNile(privateKey);
        //ApiWrapper apiWrapper = new ApiWrapper("grpc.nile.trongrid.io:50051", "grpc.nile.trongrid.io:50061", "0x" + privateKey);
        if (amount < 1) {
            log.error("获得能量或者带宽失败，错误信息:{}", "amount数值不能小于1");
            return null;
        }
        amount = amount * 1000000;
        System.out.println(amount);
        try {
            //资源委派
            Response.TransactionExtention transaction = apiWrapper.freezeBalanceV2(owneraddress, amount, resourcecode);
            Chain.Transaction signedTxn = apiWrapper.signTransaction(transaction);
            String txid = apiWrapper.broadcastTransaction(signedTxn);
            log.info("交易id==>{}", txid);
            return txid;
        } catch (Exception e) {
            System.out.println(e.getMessage());
            log.error("获得能量或者带宽失败，错误信息:{}", e.toString());
        } finally {
            apiWrapper.close();
        }
        return null;
    }

    public String unfreeze(long amount, String owneraddress, String privateKey, int resourcecode) {
        ApiWrapper apiWrapper = ApiWrapper.ofMainnet(privateKey, apiKey);
        //ApiWrapper apiWrapper = ApiWrapper.ofNile(privateKey);
        //ApiWrapper apiWrapper = new ApiWrapper("grpc.nile.trongrid.io:50051", "grpc.nile.trongrid.io:50061", "0x" + privateKey);
        if (amount < 1) {
            log.error("解冻能量或者带宽失败，错误信息:{}", "amount数值不能小于1");
            return null;
        }
        amount = amount * 1000000;
        try {
            //资源委派
            Response.TransactionExtention transaction = apiWrapper.unfreezeBalanceV2(owneraddress, amount, resourcecode);
            Chain.Transaction signedTxn = apiWrapper.signTransaction(transaction);
            String txid = apiWrapper.broadcastTransaction(signedTxn);
            log.info("交易id==>{}", txid);
            return txid;
        } catch (Exception e) {
            System.out.println(e.getMessage());
            log.error("解冻能量或者带宽失败，错误信息:{}", e.toString());
        } finally {
            apiWrapper.close();
        }
        return null;
    }


    //租用带宽
    //amount:冻结资金，单位是sun。amount最小为 1,000,000 sun, 即1TRX
    //resource：冻结获取的资源，0为Bandwidth Point，1为Energy。默认为0
    //receiverAddress：接收资源的账户
    //每冻结1TRX，就可以获得1单位
    //ResourceCode:0 BANDWIDTH, 1 ENERGY
    public String delegateResource(double amount, String owneraddress, int resourcecode, String receiveAddress, String privateKey) {
        ApiWrapper apiWrapper = ApiWrapper.ofMainnet(privateKey, apiKey);
        //ApiWrapper apiWrapper = ApiWrapper.ofNile(privateKey);
        //ApiWrapper apiWrapper = new ApiWrapper("grpc.nile.trongrid.io:50051", "grpc.nile.trongrid.io:50061", "0x" + privateKey);
        if (amount < 1) {
            log.error("委派能量或者带宽失败，错误信息:{}", "amount数值不能小于1");
            return null;
        }
        amount = amount * 1000000;
        System.out.println("amount" + amount);
        try {
            //资源委派
            Response.TransactionExtention transaction = apiWrapper.delegateResource(owneraddress, (long) amount, resourcecode, receiveAddress, false);
            Chain.Transaction signedTxn = apiWrapper.signTransaction(transaction);
            String txid = apiWrapper.broadcastTransaction(signedTxn);
            log.info("交易id==>{}", txid);
            return txid;
        } catch (Exception e) {
            System.out.println(e.getMessage());
            log.error("委派能量或者带宽失败，错误信息:{}", e.toString());
        } finally {
            apiWrapper.close();
        }
        return null;
    }

    //解冻账户
    //resource：解冻失去的资源，0为Bandwidth Point，1为Energy。默认为0
    //receiverAddress：接收资源的账户
    //amount: The number of canceled delegate resource shares, the unit is sun
    public String unDelegateResource(int resourcecode, double amount, String owneraddress, String receiveAddress, String privateKey) {
        ApiWrapper apiWrapper = ApiWrapper.ofMainnet(privateKey, apiKey);
        //ApiWrapper apiWrapper = ApiWrapper.ofNile(privateKey);
        //ApiWrapper apiWrapper = new ApiWrapper("grpc.nile.trongrid.io:50051", "grpc.nile.trongrid.io:50061", "0x" + privateKey);
        amount = amount * 1000000;
        try {
            Response.TransactionExtention transaction = apiWrapper.undelegateResource(owneraddress, (long) amount, resourcecode, receiveAddress);
            Chain.Transaction signedTxn = apiWrapper.signTransaction(transaction);
            String txid = apiWrapper.broadcastTransaction(signedTxn);
            log.info("交易id==>{}", txid);
            return txid;
        } catch (Exception e) {
            System.out.println(e.getMessage());
            log.error("回收能量或者带宽失败，错误信息:{}", e.toString());
        } finally {
            apiWrapper.close();
        }
        return null;
    }

    //查看剩余能量或者带宽
    public Long[] getAccountResource(String owneraddress, String privateKey) {
        ApiWrapper apiWrapper = ApiWrapper.ofMainnet(privateKey, apiKey);
        //ApiWrapper apiWrapper = ApiWrapper.ofNile(privateKey);
        //ApiWrapper apiWrapper = new ApiWrapper("grpc.nile.trongrid.io:50051", "grpc.nile.trongrid.io:50061", "0x" + privateKey);
        try {
            Long[] result = new Long[2];
            Response.AccountResourceMessage response = apiWrapper.getAccountResource(owneraddress);
//            System.out.println(response.getNetUsed());
//            System.out.println(response.getFreeNetLimit());
//            System.out.println(response.getFreeNetUsed());
            //600+这个值
            result[0] = response.getNetLimit() + 600 - response.getFreeNetUsed();
            result[1] = response.getEnergyLimit();
            return result;
        } catch (Exception e) {
            System.out.println(e.getMessage());
            log.error("获取能量或者带宽信息失败，错误信息:{}", e.toString());
        } finally {
            apiWrapper.close();
        }
        return null;
    }

    //查看租用列表
    //查询账户给哪些账户委派了资源
    //场景1：查询账户给哪些账户委派了资源
    //
    //step0：获得要查询的账户的地址。
    //step1：通过GetDelegatedResourceAccountIndex接口，查询获得所有与该账户发生资源委派的其他地址。
    //message DelegatedResourceAccountIndex {
    //    bytes account = 1;
    //    repeated bytes fromAccounts = 2;
    //    repeated bytes toAccounts = 3;
    //  }
    //BytesMessage：查询的地址
    //account：查询的地址
    //fromAccounts：从哪些账户中获得了资源
    public List<ByteString> getDelegatedResourceFromAccountIndex(String owneraddress, String privateKey) {
        ApiWrapper apiWrapper = ApiWrapper.ofMainnet(privateKey, apiKey);
        //ApiWrapper apiWrapper = ApiWrapper.ofNile(privateKey);
        //ApiWrapper apiWrapper = new ApiWrapper("grpc.nile.trongrid.io:50051", "grpc.nile.trongrid.io:50061", "0x" + privateKey);
        try {
            return apiWrapper.getDelegatedResourceAccountIndex(owneraddress).getFromAccountsList();
        } catch (Exception e) {
            System.out.println(e.getMessage());
            log.error("查询从哪些账户中获得了资源能量或者带宽失败，错误信息:{}", e.toString());
        } finally {
            apiWrapper.close();
        }
        return null;
    }

    //查询最多可以租用的带宽和能量数值
    //使用 delegateResource 获取 OwnerAddress 可以委托的最大大小
    //所有者地址
    //启动委托的账户地址，可选，默认为登录账户地址。
    //类型  0 带宽，1 能量
    public long getCanDelegatedMaxSize(String owneraddress, String privateKey, int type) {
        ApiWrapper apiWrapper = ApiWrapper.ofMainnet(privateKey, apiKey);
        //ApiWrapper apiWrapper = ApiWrapper.ofNile(privateKey);
        //ApiWrapper apiWrapper = new ApiWrapper("grpc.nile.trongrid.io:50051", "grpc.nile.trongrid.io:50061", "0x" + privateKey);
        try {
            return apiWrapper.getCanDelegatedMaxSize(owneraddress, type);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            log.error("查询从哪些账户中获得了资源能量或者带宽失败，错误信息:{}", e.toString());
        } finally {
            apiWrapper.close();
        }
        return -1L;
    }

    //toAccounts：给哪些账户中委派了资源
    public List<String> getDelegatedResourceToAccountIndex(String owneraddress, String privateKey) {
        ApiWrapper apiWrapper = ApiWrapper.ofMainnet(privateKey, apiKey);
        //ApiWrapper apiWrapper = ApiWrapper.ofNile(privateKey);
        //ApiWrapper apiWrapper = new ApiWrapper("grpc.nile.trongrid.io:50051", "grpc.nile.trongrid.io:50061", "0x" + privateKey);
        try {
            List<ByteString> accounts = apiWrapper.getDelegatedResourceAccountIndexV2(owneraddress).getToAccountsList();

            List<String> address = new ArrayList<>();
            for (ByteString account : accounts) {
                address.add(Base58Check.bytesToBase58(account.toByteArray()));
            }
            return address;
        } catch (Exception e) {
            System.out.println(e.getMessage());
            log.error("查询给哪些账户中委派了资源能量或者带宽失败，错误信息:{}", e.toString());
        } finally {
            apiWrapper.close();
        }
        return null;
    }

    //查询账户给某个账户委派了多少资源
    //DelegatedResourceList:只包含一个元素
    //from:发起资源委派的地址
    //to:接受资源委派的地址
    //frozen_balance_for_bandwidth:委派的带宽
    //frozen_balance_for_energy:委派的energy
    //expire_time_for_bandwidth:委派的带宽解冻时间
    //expire_time_for_energy:委派的energy解冻时间
    public List<Object> getDelegatedResource(String owneraddress, String receiveAddress, String privateKey) {
        ApiWrapper apiWrapper = ApiWrapper.ofMainnet(privateKey, apiKey);
        //ApiWrapper apiWrapper = ApiWrapper.ofNile(privateKey);
        //ApiWrapper apiWrapper = new ApiWrapper("grpc.nile.trongrid.io:50051", "grpc.nile.trongrid.io:50061", "0x" + privateKey);
        try {
            List<Object> result = new ArrayList<>();
            Map<String, Object> map = new HashMap<>();
            List<Response.DelegatedResource> response = apiWrapper.getDelegatedResourceV2(owneraddress, receiveAddress).getDelegatedResourceList();
            for (Response.DelegatedResource response1 : response) {
                map.put("ExpireTimeForBandwidth", response1.getExpireTimeForBandwidth());
                map.put("FrozenBalanceForEnergy", response1.getFrozenBalanceForEnergy());
                map.put("ExpireTimeForEnergy", response1.getExpireTimeForEnergy());
                map.put("To", Base58Check.bytesToBase58(response1.getTo().toByteArray()));
                map.put("From", Base58Check.bytesToBase58(response1.getFrom().toByteArray()));
                result.add(map);
            }
            return result;
        } catch (Exception e) {
            System.out.println(e.getMessage());
            log.error("查询账户给某个账户委派了多少资源，错误信息:{}", e.toString());
        } finally {
            apiWrapper.close();
        }
        return null;
    }

}
